﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.IO;
using Lyh.ImageTool.Properties;

namespace Lyh.ImageTool
{
    public class CursorManager
    {
        public static readonly Cursor Arrow = CreateCursor(Resources.ArrowD);
        public static readonly Cursor Cross = CreateCursor(Resources.Cross);
        public static readonly Cursor SizeAll = CreateCursor(Resources.SizeAll);
        public static readonly Cursor SizeNESW = CreateCursor(Resources.SizeNESW);
        public static readonly Cursor SizeNS = CreateCursor(Resources.SizeNS);
        public static readonly Cursor SizeNWSE = CreateCursor(Resources.SizeNWSE);
        public static readonly Cursor SizeWE = CreateCursor(Resources.SizeWE);

        private CursorManager() { }

        public static Cursor CreateCursor(Bitmap cursor, Point hotPoint)
        {
            int hotX = hotPoint.X;
            int hotY = hotPoint.Y;
            using (Bitmap cursorBmp = new Bitmap(
                cursor.Width * 2 - hotX,
                cursor.Height * 2 - hotY,
                PixelFormat.Format32bppArgb))
            {
                using (Graphics g = Graphics.FromImage(cursorBmp))
                {
                    g.Clear(Color.FromArgb(0, 0, 0, 0));
                    g.DrawImage(
                        cursor,
                        cursor.Width - hotX,
                        cursor.Height - hotY,
                        cursor.Width,
                        cursor.Height);
                    g.Flush();
                }
                return new Cursor(cursorBmp.GetHicon());
            }
        }

        public static Cursor CreateCursor(string fileName)
        {
            IntPtr cursorHandle = LoadCursorFromFile(fileName);
            return new Cursor(cursorHandle);
        }

        public static Cursor CreateCursor(byte[] buffer)
        {
            FileStream fs = new FileStream("TempCursor.dat", FileMode.Create);
            fs.Write(buffer, 0, buffer.Length);
            fs.Close();
            return CreateCursor("TempCursor.dat");
        }

        [DllImport("user32.dll")]
        private static extern IntPtr LoadCursorFromFile(string fileName);

        [DllImport("user32.dll")]
        private static extern uint DestroyCursor(IntPtr cursorHandle);
    }
}
